package resource

import (
	"mallgo/internal/common/response"
	"mallgo/internal/resources/cart/api/domain/request"
	"mallgo/internal/resources/cart/model"

	"gorm.io/gorm"
)

type CartResource struct {
	db *gorm.DB
}

func NewCartResource(db *gorm.DB) *CartResource {
	return &CartResource{
		db: db,
	}
}

// AddToCart 添加商品到购物车
func (r *CartResource) AddToCart(req *request.CartAddRequest) *response.ResponseObject {
	// 检查是否已存在相同商品
	var existCart model.Cart
	err := r.db.Where("user_id = ? AND product_id = ? AND sku_id = ?",
		req.UserID, req.ProductID, req.SkuID).First(&existCart).Error

	if err == nil {
		// 已存在则更新数量
		existCart.Num += req.Num
		if err := r.db.Save(&existCart).Error; err != nil {
			return response.Error(500, "更新购物车失败")
		}
		return response.Success(existCart)
	}

	// 不存在则新增
	cart := model.Cart{
		UserID:      req.UserID,
		ProductID:   req.ProductID,
		ProductName: req.ProductName,
		SkuID:       req.SkuID,
		SkuName:     req.SkuName,
		Num:         req.Num,
		Price:       req.Price,
		ImageURL:    req.ImageURL,
		Selected:    1, // 默认选中
	}

	if err := r.db.Create(&cart).Error; err != nil {
		return response.Error(500, "添加购物车失败")
	}

	return response.Success(cart)
}

// UpdateCart 更新购物车商品数量
func (r *CartResource) UpdateCart(req *request.CartUpdateRequest) *response.ResponseObject {
	if err := r.db.Model(&model.Cart{}).Where("id = ?", req.ID).
		Update("num", req.Num).Error; err != nil {
		return response.Error(500, "更新购物车失败")
	}
	return response.Success(nil)
}

// DeleteCart 删除购物车商品
func (r *CartResource) DeleteCart(cartId int64) *response.ResponseObject {
	if err := r.db.Delete(&model.Cart{}, cartId).Error; err != nil {
		return response.Error(500, "删除购物车失败")
	}
	return response.Success(nil)
}

// ListCart 获取购物车列表
func (r *CartResource) ListCart(userId int64) *response.ResponseObject {
	var carts []model.Cart
	if err := r.db.Where("user_id = ?", userId).Find(&carts).Error; err != nil {
		return response.Error(500, "获取购物车列表失败")
	}
	return response.Success(carts)
}

// SelectCart 选中/取消选中购物车商品
func (r *CartResource) SelectCart(req *request.CartSelectRequest) *response.ResponseObject {
	if err := r.db.Model(&model.Cart{}).Where("id = ?", req.ID).
		Update("selected", req.Selected).Error; err != nil {
		return response.Error(500, "更新购物车选中状态失败")
	}
	return response.Success(nil)
}
